package com.lsp.java.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lisp
 * @date 2023/2/28 16:15
 * @describe: 集合工具类
 **/
public class ListUtils {
    private ListUtils() {
        // 私有，禁止实例
    }

    /**
     * 集合分组，每页大小固定
     *
     * @param list     集合
     * @param pagesize 分组
     * @return List<List < T>>
     */
    public static <T> List<List<T>> splitByPageSize(List<T> list, int pagesize) {
        // 确定数据要分几次插入
        List<List<T>> lists = new ArrayList<>();
        int total = list.size();
        // 批次次数
        int loopTimes = (total - 1) / pagesize + 1;

        for (int i = 0; i < loopTimes; ++i) {
            int fromIndex = i * pagesize;
            int toIndex = (i + 1) * pagesize;

            lists.add(new ArrayList<>(list.subList(fromIndex, Math.min(toIndex, total))));
        }
        return lists;

    }

    /**
     * 集合分组，组数是固定的
     *
     * @param list    集合
     * @param pageNum 分组
     * @return List<List < T>>
     */
    public static <T> List<List<T>> splitByPageNum(List<T> list, int pageNum) {
        // 确定数据要分几次插入
        List<List<T>> lists = new ArrayList<>();
        int total = list.size();
        int pagesize = total / pageNum;
        int remainder = total % pageNum;
        int fromIndex = 0;

        for (int i = 0; i < pageNum; ++i) {
            int toIndex = fromIndex + pagesize;
            if (remainder > 0) {
                toIndex++;
                remainder--;
            }
            if (fromIndex < total) {
                lists.add(new ArrayList<>(list.subList(fromIndex, Math.min(toIndex, total))));
            } else {
                lists.add(new ArrayList<>());
            }
            fromIndex = toIndex;
        }
        return lists;

    }
}
